var express = require('express');
var router = express.Router();
const fs = require('fs');
const path = require('path');
const query = require('../conn/conn');
const sendMail = require('../library/sendMail');

router.get('/all', async (req, res, next) => {
    let result =  await query('select * from users');
    res.send(result);
});

router.get('/getcode', (req, res, next) => {
    fs.writeFile(path.join(__dirname, '..', 'temp', req.query.email), sendMail(req.query.email), 'utf8', err => {
        if (err) console.log(err);
        res.send({ msg: '邮件已发送', success: 1 });
    });
});

router.post('/login_zc', (req, res, next) => {
    fs.readFile(path.join(__dirname, '..', 'temp', req.body.email), 'utf8', (err, data) => {
        if (err) {
            console.log(err);
            res.send({ success: 0, msg: '输入的邮箱和上次不一致', error: 101 });
        } else if (req.body.code === data) {
            res.send({ success: 1, msg: '注册成功' });
            fs.unlink(path.join(__dirname, '..', 'temp', req.body.email), err => {
                if (err) console.log(err);
                console.log('文件已删除');
            });
            query(`insert into users (email,password) values (\"${req.body.email}\",\"${req.body.password}\")`);
        } else {
            res.send({ success: 0, msg: '验证码不正确', error: 102 });
        }
    });
});
module.exports = router;
